﻿#include "dialog.h"
#include "ui_dialog.h"

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);

    QDir indexDir(CACHE_INDEX);
    QString indexLocation=indexDir.absolutePath();
    if(!indexDir.exists())
        indexDir.mkpath(indexLocation);

    if(cdb.open(indexLocation.toStdString()))
        ui->reply->setText("All Things Good");
    else
        ui->reply->setText("DB CAN NOT OPEN");

    player=new AVPlayer(this);
    startSpeechSynthesizer();
}

Dialog::~Dialog()
{
    stopSpeechSynthesizer();
    delete ui;
}

void Dialog::startSpeechSynthesizer()
{
    synthesizer=new BaiduSpeechSynthesizer;
    connect(synthesizer,&BaiduSpeechSynthesizer::errorMsg,
            this,&Dialog::onErrorMsg);
    connect(synthesizer,&BaiduSpeechSynthesizer::finished,
            this,&Dialog::onSynthesisFinished);
    connect(this,&Dialog::synthesis,
            synthesizer,&BaiduSpeechSynthesizer::requestStatement);

    connect(&synthesizerThread,&QThread::finished,
            synthesizer,&QObject::deleteLater);

    synthesizer->moveToThread(&synthesizerThread);
    synthesizerThread.start();
}

void Dialog::stopSpeechSynthesizer()
{
    synthesizerThread.quit();
    synthesizerThread.wait();
}

void Dialog::onErrorMsg(const QString &msg)
{
    qDebug() << msg;
}

void Dialog::play(const QString &fileName)
{
    if(QFile::exists(fileName))
    {
        player->setFile(fileName);
        player->play();
    }
}

void Dialog::onSynthesisFinished(const QString &text, const QString &fileName)
{
    cache.insert(text,fileName);
    cdb.put(text,fileName);
    play(fileName);
}

void Dialog::on_btn_submit_clicked()
{
}

void Dialog::on_btn_ask_clicked()
{
}

void Dialog::on_btn_syn_clicked()
{
    QString text=ui->statement->text().trimmed();
    if(text.isEmpty())
        return;

    if(cache.contains(text))
    {
        play(cache.value(text));
        return;
    }
    else
    {
        QString value=cdb.get(text);
        if(value != RET_NONE)
        {
            cache.insert(text,value);
            play(value);
            return;
        }

        emit synthesis(text);
        ui->statement->clear();
    }
}
